package org.ix.dynamicapis.controller;

import io.swagger.annotations.Api;
import org.ix.dynamicapis.plugins.PluginConfig;
import org.ix.dynamicapis.plugins.PluginsFactory;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

@Api(tags = {"插件相关接口"})
@CrossOrigin
@RequestMapping("/plugin")
@RestController
@Validated
public class PluginController {

    final PluginsFactory pluginsFactory;
    final ApplicationContext applicationContext;

    @Autowired
    public PluginController(PluginsFactory pluginsFactory, ApplicationContext applicationContext) {
        this.pluginsFactory = pluginsFactory;
        this.applicationContext = applicationContext;
    }

    @GetMapping("list")
    public ResponseEntity<Collection<PluginConfig>> list() throws IOException {
        return ResponseEntity.ok(pluginsFactory.flushConfigs());
    }

    @GetMapping("active")
    public ResponseEntity<String> enablePlugin(@RequestParam("id") String id) {
        pluginsFactory.enable(id);
        return ResponseEntity.ok("success");
    }

    @GetMapping("disable")
    public ResponseEntity<String> disable(@RequestParam("id") String id) {
        pluginsFactory.disable(id);
        return ResponseEntity.ok("success");
    }

    @GetMapping("get-classes")
    public ResponseEntity<List<String>> getBeans() {
        List<String> beans = new LinkedList<>();
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String name : beanDefinitionNames) {
            Object bean = applicationContext.getBean(name);
            if (bean == this || !(bean instanceof Advised)) continue;
//            Class<?> clazz = bean.getClass();
//            if (clazz.getAnnotation(Controller.class) == null && clazz.getAnnotation(RestController.class) == null) continue;
            beans.add(name);
        }
        return ResponseEntity.ok(beans);

    }
}
